package com.medata.controller;
/*
 *@ClassName: TestController
 *@Description: TODO
 *@author: zb
 *@date: 2019-03-23 8:11
 *@version: 1.0
 */

import com.google.gson.Gson;
import com.medata.dataObject.*;
import com.medata.service.DatabaselistService;
import com.medata.service.GlobalsettingService;
import com.medata.service.TemplatefieldsService;
import com.medata.service.impl.AccountServiceImpl;
import com.medata.service.impl.CategoryServiceImpl;
import com.medata.service.impl.UserRoleServiceImpl;
import com.medata.utils.MenuUtil;
import com.medata.utils.PreUtils;
import com.medata.utils.SolrUtils;
import com.medata.vo.SysMenu;
import com.medata.vo.UrlVo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Controller
@Slf4j
@Api
public class LoginController {
    @Autowired
    private GlobalsettingService globalsettingService;
    @Autowired
    private DatabaselistService databaselistService;
    @Autowired
    private TemplatefieldsService templatefieldsService;
    @Autowired
    private AccountServiceImpl accountService;
    @Autowired
    private UserRoleServiceImpl userRoleService;
    @Autowired
    private CategoryServiceImpl categoryService;
    @Value("${solrPath}")
    private String solrPath;
    @Value("${FilePath}")
    private String filePath;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public ModelAndView login(HttpSession session, String token, String name, String password, HttpServletResponse response, HttpServletRequest request)throws IOException {
        String ip5=request.getRemoteAddr()+"5";
        ValueOperations<String, String> ops1 = redisTemplate.opsForValue();
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken stoken = new UsernamePasswordToken(name, password);
        ModelAndView mv=new ModelAndView();
        mv.addObject("username",name);
        List<UrlVo> urlList=new ArrayList<>();
       try {
           subject.login(stoken);
           Account account=accountService.findByUserName(name);
           UserRole userRole=userRoleService.findByRoleId(account.getRoleId());
           if (account.getStatus()==null||!account.getStatus()){
               response.setHeader("Content-type", "text/html;charset=UTF-8");
               PrintWriter writer = response.getWriter();
               writer.print("<script type='text/javascript'>alert('该账户已被停用');history.go(-1)</script>");
               writer.flush();
               writer.close();
           }
           String role=userRole.getRoleName();
           if (role.equals("编目人员")){
               List<Category> all = new ArrayList<>();
               String dbids = account.getDbids();
               if (dbids!=null&&!dbids.isEmpty()){
                   String[] ids=dbids.split(",");
                   for (String i:ids){
                       Category category = categoryService.findByDbid(Integer.valueOf(i));
                       all.add(category);
                   }
               }
               for (Category category:all){
                   UrlVo urlVo=new UrlVo();
                   urlVo.setUrl("editor/zlpost/"+category.getDbid());
                   urlVo.setDesc(category.getDc());
                   urlList.add(urlVo);
               }
               mv.addObject("UrlList",urlList);
               mv.setViewName("index");
               return mv;
           }if (role.equals("管理员")){
               mv.setViewName("index");
               return mv;
           }if ((role.equals("审核人员"))){
               mv.setViewName("index");
               return mv;
           }
       }catch (AuthenticationException ae){
            log.info("用户名or密码错误or错误次数过多");
           ValueOperations<String, String> ops = redisTemplate.opsForValue();
           String s = ops.get(ip5);
           response.setHeader("Content-type", "text/html;charset=UTF-8");
           PrintWriter writer = response.getWriter();
           if (s!=null){
               if (Integer.valueOf(s)>5){
                   writer.print("<script type='text/javascript'>alert('密码错误次数太多,请稍后登入');history.go(-1)</script>");
                   writer.flush();
                   writer.close();
                   return null;
               }
               ops.set(ip5,String.valueOf(Integer.valueOf(s)+1),5,TimeUnit.MINUTES);
           }else {
               ops.set(ip5,"1",5,TimeUnit.MINUTES);
           }
           writer.print("<script type='text/javascript'>alert('账号or密码错误:错误5次以上将锁定账户');history.go(-1)</script>");
           writer.flush();
           writer.close();
           return null;
       }

       Object keyToken1 = session.getAttribute("keyToken");
       if (token!=null){
           String kt = keyToken1.toString();
           if (kt.equals(token)){
               session.removeAttribute("keyToken");
               return mv;
           }
       }
        PrintWriter writer = response.getWriter();
        writer.print("<script type='text/javascript'>alert('异常登入');history.go(-1)</script>");
        writer.flush();
        writer.close();
        return null;


    }
    @RequestMapping(value = "/notLogin", method = RequestMethod.GET)
    public String notLogin(HttpSession session) {
        String uid = UUID.randomUUID().toString();
        session.setAttribute("keyToken",uid);
        return "notlogin";
    }

    @RequestMapping(value = "/notRole", method = RequestMethod.GET)
    public String notRole() {
        return "error/403";
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public ModelAndView logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        ModelAndView mv=new ModelAndView();
        mv.setViewName("notlogin");
        return mv;
    }

    @RequestMapping(value = "/menuList",method = RequestMethod.GET)
    @ResponseBody
    public List<SysMenu> get(){
        Object username = SecurityUtils.getSubject().getPrincipal();
        String name = ObjectUtils.nullSafeToString(username);
        Account account = accountService.findByUserName(name);
        List<SysMenu> sLists=new ArrayList<>();
        if (account.getRoleId()==2){
            List<Category> categories = new ArrayList<>();
            String dbids = account.getDbids();
            if (dbids!=null&&!dbids.isEmpty()){
                String[] ids=dbids.split(",");
                for (String i:ids){
                    Category category = categoryService.findByDbid(Integer.valueOf(i));
                    categories.add(category);
                }
            }
            sLists = MenuUtil.getEditorMenu(categories);
        }else if (account.getRoleId()==1){
            sLists=MenuUtil.getAdminMenu();
        }else if (account.getRoleId()==4){
            List<Category> categories = categoryService.findAll();
            sLists=MenuUtil.getAuditorMenu(categories);
        }
        return sLists;
    }

    @RequestMapping(value = "/welcome",method = RequestMethod.GET)
    public String welcome(){
        return "welcome";
    }

    @RequestMapping(value = "/start",method = RequestMethod.GET)
    @ResponseBody
    public String start(){
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        Gson gson=new Gson();
        for (int i=1;i<50;i++){
            List<Templatefields> templatefieldsList = templatefieldsService.getByDbidOrderBySequence(i);
            if (templatefieldsList!=null&&templatefieldsList.size()>1){
                ops.set(String.valueOf(templatefieldsList.get(0).getDbid()),gson.toJson(templatefieldsList));
            }
        }
        List<Databaselist> databaselists = databaselistService.findAll();
        for (Databaselist database:databaselists){
            SolrUtils.insertCore(globalsettingService,database.getDbname());
        }
        PreUtils.prePronunciations(redisTemplate,solrPath);
//        ExcelUtils.preExcels();
        return "初始化完毕";
    }

    @RequestMapping("/")
    public String index(HttpSession session){
        String uid = UUID.randomUUID().toString();
        session.setAttribute("keyToken",uid);
        return "notlogin";
    }

    @RequestMapping(value = "/restartSession",method = RequestMethod.GET)
    @ResponseBody
    public String restartSession(){
        return null;
    }


}
